package com.coco.seck.mqqueue;

import com.coco.common.constant.Constant;
import com.coco.seck.mapper.SeckillGoodsMapper;
import com.coco.seck.pojo.TbSeckillGoods;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author HanSama
 * @date 2021年07月19日 15:34
 */
@Component
public class SecGoodsNumQueue {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;


    /**
     * secGoodsNumOne消费者调用Redis同步MYSQL方法
     *
     * @param tbSeckillGoods
     * @author HanSama
     * @date 2021/7/19 17:13
     */
    @RabbitListener(queues = "secGoodsNumOne")
    @RabbitHandler
    public void secGoodsNumOne(TbSeckillGoods tbSeckillGoods) {

        syncMysqlGoodsStuckCount(tbSeckillGoods);
    }


    /**
     * 检查Redis同步库存
     *
     * @param seckillGoods
     * @author HanSama
     * @date 2021/7/19 16:58
     */
    private void syncMysqlGoodsStuckCount(TbSeckillGoods seckillGoods) {
        Long id = seckillGoods.getId();
        Integer stockCount = seckillGoods.getStockCount();

        //获取redis剩余库存
        Integer stock = (Integer) redisTemplate.opsForValue().get(Constant.RedisKeyConstant.GOODS_KEY_TEMPLATE + id);

        if (stock != null) {
            //计算剩余库存
            stockCount -= stock;
            seckillGoods.setStockCount(seckillGoods.getStockCount() - stockCount);

            //修改MySql剩余库存
            seckillGoodsMapper.updateSeckGoods(seckillGoods);

            //删除Redis商品缓存
            redisTemplate.delete(Constant.RedisKeyConstant.GOODS_KEY_TEMPLATE + id);
        }
    }


}
